package commons.utils;

public class UtilsCalcul
{

	static public double min(double d1, double d2)	{return (d1 <= d2) ? d1 : d2;}
	static public double max(double d1, double d2)	{return (d1 <= d2) ? d2 : d1;}
	
	static public double round(double val, int nbDec) {
//		long temp = (long) (d * Math.pow(10,nbDec));
//		return ((double)temp) / Math.pow(10,nbDec);
		double augmentation = Math.pow(10, nbDec);
//		return (double)( (long)(val * augmentation + .5) ) / augmentation;
		return Math.round(val * augmentation) / augmentation; // gere bien les valeurs <0 contrairement à la ligne precedente
	}

	static public double round1(double val) {
		double augmentation = 10.0;
		return Math.round(val * augmentation) / augmentation;
	}
		
	static public double round2(double val) {
		double augmentation = 100.0;
		return Math.round(val * augmentation) / augmentation;
	}

	static public double round3(double val) {
		double augmentation = 1000.0;
		return Math.round(val * augmentation) / augmentation;
	}
	
	public static double parseDouble_v2(String sDouble) throws Exception
	{
		double res = 0;
		int start = 0;
		boolean bNeg = false;
		if (sDouble.charAt(start) == '-')
		{
			bNeg = true;
			start = 1;
		}

		int i;

		// Lecture partie entière
		for (i = start; i < sDouble.length(); i++)
		{
			char c = sDouble.charAt(i);

			if (c == '.')
				break;

			if (c < '0' || c > '9')
				throw new Exception("Format invalide : " + sDouble);

			res *= 10;
			res += (c - '0');
		}

		// Lecture mantisse
		double mantisse = 0;
		if (sDouble.charAt(i) == '.')
		{
			for (int j = sDouble.length() - 1; j > i; j--)
			{
				char c = sDouble.charAt(j);

				if (c < '0' || c > '9')
					throw new Exception("Format invalide : " + sDouble);

				mantisse += (c - '0');
				mantisse /= 10;
			}

			res += mantisse;
		}


		if (bNeg)
			res = -res;
		return res;
	}

	public static double parseDouble(String sDouble) throws Exception
	{
		double res = 0;
		char[] tabchar = sDouble.toCharArray();
		int start = 0;
		boolean bNeg = false;
		if (tabchar[start] == '-')
		{
			bNeg = true;
			start = 1;
		}

		int i;

		// Lecture partie entière
		for (i = start; i < tabchar.length; i++)
		{
			char c = tabchar[i];

			if (c == '.')
				break;

			if (c < '0' || c > '9')
				throw new Exception("Format invalide : " + sDouble);

			res *= 10;
			res += (c - '0');
		}

		// Lecture mantisse
		double mantisse = 0;
		if (tabchar[i] == '.')
		{
			for (int j = tabchar.length - 1; j > i; j--)
			{
				char c = tabchar[j];

				if (c < '0' || c > '9')
					throw new Exception("Format invalide : " + sDouble);

				mantisse += (c - '0');
				mantisse /= 10;
			}

			res += mantisse;
		}


		if (bNeg)
			res = -res;
		return res;
	}

}
